from functools import partial

import torch
from torch import Tensor
from torch import nn
from torch.nn import Module
from torch.nn.init import xavier_uniform_
import torch.nn.functional as F

from positional_embedding import PositionalEncoding
from transformers import UniTransformer, CrossTransformer, CIM


class MulT(Module):
  r"""A transformer model. User is able to modify the attributes as needed. The architecture
    is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer,
    Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and
    Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information
    Processing Systems, pages 6000-6010. Users can build the BERT(https://arxiv.org/abs/1810.04805)
    model with corresponding parameters.

    Args:
        d_model: the number of expected features in the encoder/decoder inputs (default=512).
        nhead: the number of heads in the multiheadattention models (default=8).
        num_encoder_layers: the number of sub-encoder-layers in the encoder (default=6).
        num_decoder_layers: the number of sub-decoder-layers in the decoder (default=6).
        dim_feedforward: the dimension of the feedforward network model (default=2048).
        dropout: the dropout value (default=0.1).
        activation: the activation function of encoder/decoder intermediate layer, relu or gelu (default=relu).

    Examples::
        >>> transformer_model = MulT(nhead=16, num_encoder_layers=12)
        >>> src = torch.rand((10, 32, 512))
        >>> tgt = torch.rand((20, 32, 512))
        >>> out = transformer_model(src, tgt)

    Note: A full example to apply nn.Transformer module for the word language model is available in
    https://github.com/pytorch/examples/tree/master/word_language_model
    """

  def __init__(self, hyp_params) -> None:
    super(MulT, self).__init__()

    # model size control
    self.orig_d_l, self.orig_d_a, self.orig_d_v = hyp_params.orig_d_l, hyp_params.orig_d_a, hyp_params.orig_d_v
    self.d_model = hyp_params.dims_per_head * hyp_params.num_heads
    self.l_len, self.a_len, self.v_len = hyp_params.l_len, hyp_params.a_len, hyp_params.v_len
    self.num_heads = hyp_params.num_heads
    self.nlayers = hyp_params.nlayers
    output_dim = hyp_params.output_dim  # This is actually not a hyperparameter :-)
    # 1d conv
    self.kernel_size_a = hyp_params.kernel_size_a
    self.kernel_size_l = hyp_params.kernel_size_l
    self.kernel_size_v = hyp_params.kernel_size_v
    # shrinked search space for ccc/cdc
    self.kernel_size_av = hyp_params.kernel_size
    self.kernel_size_vl = hyp_params.kernel_size
    self.kernel_size_la = hyp_params.kernel_size
    self.kernel_size_al = hyp_params.kernel_size
    self.kernel_size_va = hyp_params.kernel_size
    self.kernel_size_lv = hyp_params.kernel_size
    # operation type control
    self.fusion_type = hyp_params.fusion_type
    self.fusion_layer_type = hyp_params.fusion_layer_type

    # unimodal or multimodal setting
    self.l_enable = hyp_params.l_enable
    self.a_enable = hyp_params.a_enable
    self.v_enable = hyp_params.v_enable
    self.partial_mode = self.l_enable + self.a_enable + self.v_enable
    # assuming that #dim for every nodel are the same
    combined_dim = 2 * self.partial_mode * self.d_model

    # 0. dropout for language embedding and output
    self.language_dropout = nn.Dropout(hyp_params.embed_dropout, inplace=False)
    self.output_dropout = nn.Dropout(hyp_params.out_dropout)

    # 1. Temporal convolutional layers
    self.proj_l = nn.Conv1d(
        self.orig_d_l,
        self.d_model,
        kernel_size=self.kernel_size_l * 2 + 1,
        padding=self.kernel_size_l,
        bias=False)
    self.proj_a = nn.Conv1d(
        self.orig_d_a,
        self.d_model,
        kernel_size=self.kernel_size_a * 2 + 1,
        padding=self.kernel_size_a,
        bias=False)
    self.proj_v = nn.Conv1d(
        self.orig_d_v,
        self.d_model,
        kernel_size=self.kernel_size_v * 2 + 1,
        padding=self.kernel_size_v,
        bias=False)

    # 2. Crossmodal Attentions
    if self.fusion_layer_type == 'cil' and self.fusion_type != 'ta':
      crossModule = CIM
    else:
      crossModule = CrossTransformer
    CrossT = partial(
        crossModule,
        self.d_model,
        self.num_heads,
        self.nlayers,
        relu_dropout=hyp_params.relu_dropout,
        res_dropout=hyp_params.res_dropout,
        embed_dropout=hyp_params.embed_dropout,
        l_type=self.fusion_layer_type,
        ia_type=self.fusion_type)
    if self.a_enable:
      self.cross_av = CrossT(
          kernel_size=self.kernel_size_av * 2 + 1,
          x_len=self.a_len,
          y_len=self.v_len,
          attn_dropout=hyp_params.attn_dropout_v)
      self.cross_al = CrossT(
          kernel_size=self.kernel_size_al * 2 + 1,
          x_len=self.a_len,
          y_len=self.l_len,
          attn_dropout=hyp_params.attn_dropout_l)
    if self.v_enable:
      self.cross_va = CrossT(
          kernel_size=self.kernel_size_va * 2 + 1,
          x_len=self.v_len,
          y_len=self.a_len,
          attn_dropout=hyp_params.attn_dropout_a)
      self.cross_vl = CrossT(
          kernel_size=self.kernel_size_vl * 2 + 1,
          x_len=self.v_len,
          y_len=self.l_len,
          attn_dropout=hyp_params.attn_dropout_l)
    if self.l_enable:
      self.cross_la = CrossT(
          kernel_size=self.kernel_size_la * 2 + 1,
          x_len=self.l_len,
          y_len=self.a_len,
          attn_dropout=hyp_params.attn_dropout_a)
      self.cross_lv = CrossT(
          kernel_size=self.kernel_size_lv * 2 + 1,
          x_len=self.l_len,
          y_len=self.v_len,
          attn_dropout=hyp_params.attn_dropout_v)

    # 3. Self Attentions (Could be replaced by LSTMs, GRUs, etc.)
    UniT = partial(
        UniTransformer,
        self.d_model * 2,
        self.num_heads,
        4,
        relu_dropout=hyp_params.relu_dropout,
        res_dropout=hyp_params.res_dropout,
        embed_dropout=hyp_params.embed_dropout)
    if self.a_enable:
      self.uni_a = UniT(attn_dropout=hyp_params.attn_dropout)
    if self.v_enable:
      self.uni_v = UniT(attn_dropout=hyp_params.attn_dropout)
    if self.l_enable:
      self.uni_l = UniT(attn_dropout=hyp_params.attn_dropout)

    # 4. Projection layers
    self.proj1 = nn.Linear(combined_dim, combined_dim)
    self.proj2 = nn.Linear(combined_dim, combined_dim)
    self.out_layer = nn.Linear(combined_dim, output_dim)

    self._reset_parameters()

  def forward(self, l: Tensor, a: Tensor, v: Tensor) -> Tensor:
    r"""Take in and process masked source/target sequences.

        Args:
            a, v, l: the sequence to the encoder (required).
        Shape:
            - a: :math:`(La, N, E)`.
            - v: :math:`(Lv, N, E)`.
            - l: :math:`(Ll, N, E)`.

            Note: [src/tgt/memory]_mask ensures that position i is allowed to attend the unmasked
            positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend
            while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``
            are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
            is provided, it will be added to the attention weight. 
            [src/tgt/memory]_key_padding_mask provides specified elements in the key to be ignored by
            the attention. If a ByteTensor is provided, the non-zero positions will be ignored while the zero
            positions will be unchanged. If a BoolTensor is provided, the positions with the
            value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.

            - output: :math:`(T, N, E)`.

            Note: Due to the multi-head attention architecture in the transformer model,
            the output sequence length of a transformer is same as the input sequence
            (i.e. target) length of the decode.

            where S is the source sequence length, T is the target sequence length, N is the
            batch size, E is the feature number

        Examples:
            >>> output = transformer_model(src, tgt, src_mask=src_mask, tgt_mask=tgt_mask)
        """

    if a.size(0) != v.size(0) or a.size(0) != l.size(0):
      raise RuntimeError("the batch number of src and tgt must be equal")

    a = a.transpose(1, 2)
    a = self.proj_a(a)
    a = a.permute(2, 0, 1)

    v = v.transpose(1, 2)
    v = self.proj_v(v)
    v = v.permute(2, 0, 1)

    l = self.language_dropout(l.transpose(1, 2))
    l = self.proj_l(l)
    l = l.permute(2, 0, 1)

    if self.a_enable:
      av = self.cross_av(a, v)
      al = self.cross_al(a, l)
      avl = self.uni_a(torch.cat([av, al], dim=-1))
    if self.l_enable:
      la = self.cross_la(l, a)
      lv = self.cross_lv(l, v)
      lav = self.uni_l(torch.cat([la, lv], dim=-1))
    if self.v_enable:
      va = self.cross_va(v, a)
      vl = self.cross_vl(v, l)
      val = self.uni_v(torch.cat([va, vl], dim=-1))

    # only extract the last step
    if self.partial_mode == 3:
      output = torch.cat([avl[-1], lav[-1], val[-1]], dim=-1)
    elif self.a_enable:
      output = avl[-1]
    elif self.v_enable:
      output = val[-1]
    elif self.l_enable:
      output = lav[-1]
    else:
      raise RuntimeError(f'wrong partial mode')

    # A residual block
    last_hs_proj = self.proj2(
        self.output_dropout(F.relu(self.proj1(output), inplace=False)))
    last_hs_proj += output

    output = self.out_layer(last_hs_proj)

    return output

  def _reset_parameters(self):
    r"""Initiate parameters in the transformer model."""

    for p in self.parameters():
      if p.dim() > 1:
        xavier_uniform_(p)


if __name__ == '__main__':
  from hyparams import hyparams
  hyp = hyparams()
  ks = 5
  transformer_model = MulT(hyp)
  a = torch.rand((32, hyp.a_len, hyp.orig_d_a))
  v = torch.rand((32, hyp.v_len, hyp.orig_d_v))
  l = torch.rand((32, hyp.l_len, hyp.orig_d_l))
  out = transformer_model(l, a, v)
  print(out.shape)
